<template>
  <div class="department-reports">
    <el-tabs v-model="activeTab" class="main-tabs">
      <!-- Tab 1: 员工报告查阅 -->
      <el-tab-pane label="员工报告查阅" name="employee-reports">
        <div class="employee-reports-container">
          <!-- 左侧：员工列表 -->
          <div class="sidebar">
            <div class="sidebar-header">
              <el-input 
                v-model="searchQuery" 
                placeholder="搜索员工" 
                prefix-icon="Search" 
                clearable
              />
            </div>
            <el-scrollbar height="calc(100vh - 250px)">
              <el-menu 
                :default-active="selectedEmployeeId"
                @select="handleEmployeeSelect" 
                class="employee-menu"
              >
                <el-menu-item 
                  v-for="emp in filteredEmployees" 
                  :key="emp.id" 
                  :index="emp.id.toString()"
                >
                  <el-icon><User /></el-icon>
                  <span>{{ emp.username }}</span>
                </el-menu-item>
              </el-menu>
            </el-scrollbar>
          </div>
          
          <!-- 右侧：报告列表 -->
          <div class="main-content">
            <div v-if="!selectedEmployee" class="empty-state">
              <el-empty description="请从左侧选择一位员工查看其工作报告" />
            </div>
            <div v-else class="reports-view">
              <div class="report-header">
                <div class="user-info">
                  <el-avatar :size="40">{{ selectedEmployee.username.charAt(0).toUpperCase() }}</el-avatar>
                  <h3>{{ selectedEmployee.username }} 的工作报告</h3>
                </div>
                <el-radio-group v-model="reportType" @change="fetchReports">
                  <el-radio-button label="weekly">周报</el-radio-button>
                  <el-radio-button label="monthly">月报</el-radio-button>
                  <el-radio-button label="annual">年报</el-radio-button>
                </el-radio-group>
              </div>
              
              <div v-loading="loadingReports" class="reports-list">
                <el-empty v-if="reports.length === 0" description="该时段暂无报告数据" />
                <el-timeline v-else>
                  <el-timeline-item
                    v-for="report in reports"
                    :key="report.id"
                    :timestamp="formatDate(report.created_at)"
                    placement="top"
                    :type="getTimelineColor(report)"
                  >
                    <el-card class="report-card">
                      <template #header>
                        <div class="card-header">
                          <span class="report-title">{{ getReportTitle(report) }}</span>
                          <el-tag size="small">{{ getReportStatus(report) }}</el-tag>
                        </div>
                      </template>
                      <div class="report-body">
                        <div v-if="reportType === 'weekly'">
                          <p><strong>本周成就:</strong> {{ report.achievements }}</p>
                          <p><strong>遇到的挑战:</strong> {{ report.challenges }}</p>
                          <p><strong>下周计划:</strong> {{ report.next_week_plan }}</p>
                        </div>
                        <div v-else-if="reportType === 'monthly'">
                          <p><strong>月度总结:</strong> {{ report.summary }}</p>
                          <p><strong>关键亮点:</strong> {{ report.highlights }}</p>
                        </div>
                        <div v-else>
                          <p><strong>年度总结:</strong> {{ report.summary }}</p>
                          <p><strong>主要成就:</strong> {{ report.achievements }}</p>
                        </div>
                      </div>
                    </el-card>
                  </el-timeline-item>
                </el-timeline>
              </div>
            </div>
          </div>
        </div>
      </el-tab-pane>

      <!-- Tab 2: 部门报告生成 -->
      <el-tab-pane label="部门报告生成" name="department-generate">
        <div class="department-generate-container">
          <el-card class="generate-card">
            <template #header>
              <div class="card-header">
                <span><el-icon><DataAnalysis /></el-icon> 智能生成部门汇报</span>
                <el-tag type="success">AI 驱动</el-tag>
              </div>
            </template>
            
            <el-form :inline="true" class="generate-form">
              <el-form-item label="报告类型">
                <el-select v-model="generateForm.type" style="width: 150px">
                  <el-option label="部门周报" value="weekly" />
                  <el-option label="部门月报" value="monthly" />
                  <el-option label="部门年报" value="annual" />
                </el-select>
              </el-form-item>
              
              <el-form-item label="时间范围">
                <el-date-picker
                  v-if="generateForm.type === 'weekly'"
                  v-model="generateForm.date"
                  type="week"
                  format="ww 周"
                  placeholder="选择周"
                  style="width: 200px"
                />
                <el-date-picker
                  v-else-if="generateForm.type === 'monthly'"
                  v-model="generateForm.date"
                  type="month"
                  placeholder="选择月"
                  style="width: 200px"
                />
                <el-date-picker
                  v-else
                  v-model="generateForm.date"
                  type="year"
                  placeholder="选择年"
                  style="width: 200px"
                />
              </el-form-item>
              
              <el-form-item>
                <el-button type="primary" @click="generateDepartmentReport" :loading="generating">
                  <el-icon><MagicStick /></el-icon> 开始生成
                </el-button>
              </el-form-item>
            </el-form>
            
            <el-alert
              title="说明"
              type="info"
              description="系统将自动汇总该时间段内所有员工的提交记录，并使用 AI 提炼核心成就与风险。"
              show-icon
              :closable="false"
              style="margin-bottom: 20px"
            />

            <div v-if="generatedReport" class="report-preview-container">
              <div class="preview-header">
                <h3>生成结果预览</h3>
                <div class="preview-actions">
                  <el-button @click="copyReport">复制内容</el-button>
                  <el-button type="success" @click="saveDepartmentReport">保存归档</el-button>
                </div>
              </div>
              <div class="markdown-body">
                <el-input
                  v-model="generatedReport.content"
                  type="textarea"
                  :rows="15"
                />
              </div>
            </div>
          </el-card>
        </div>
      </el-tab-pane>

      <!-- Tab 3: 工作汇报 (已保存的部门报告) -->
      <el-tab-pane label="工作汇报" name="saved-reports">
        <div class="saved-reports-container">
          <div v-loading="loadingSavedReports" class="reports-list">
            <el-empty v-if="savedReports.length === 0" description="暂无已保存的部门报告" />
            <el-timeline v-else>
              <el-timeline-item
                v-for="report in savedReports"
                :key="report.id"
                :timestamp="formatDate(report.created_at)"
                placement="top"
                type="primary"
              >
                <el-card class="report-card">
                  <template #header>
                    <div class="card-header">
                      <span class="report-title">
                        {{ report.year }}年 
                        <span v-if="report.month">{{ report.month }}月 </span>
                        <span v-if="report.week">第{{ report.week }}周 </span>
                        {{ report.type === 'weekly' ? '部门周报' : report.type === 'monthly' ? '部门月报' : '部门年报' }}
                      </span>
                      <el-button type="text" @click="copyContent(report.content)">复制</el-button>
                    </div>
                  </template>
                  <div class="markdown-body" style="white-space: pre-wrap;">
                    {{ report.content }}
                  </div>
                </el-card>
              </el-timeline-item>
            </el-timeline>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import { ref, computed, onMounted, watch } from 'vue'
import { Search, User, MagicStick, DataAnalysis } from '@element-plus/icons-vue'
import axios from 'axios'
import { useAuthStore } from '../stores/auth'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'

export default {
  name: 'DepartmentReports',
  components: { Search, User, MagicStick, DataAnalysis },
  setup() {
    const authStore = useAuthStore()
    const activeTab = ref('employee-reports')
    
    // Employee List
    const employees = ref([])
    const searchQuery = ref('')
    const selectedEmployeeId = ref('')
    const selectedEmployee = ref(null)
    
    // Reports Data
    const reportType = ref('weekly')
    const reports = ref([])
    const loadingReports = ref(false)
    
    // Generation
    const generateForm = ref({
      type: 'weekly',
      date: new Date()
    })
    const generating = ref(false)
    const generatedReport = ref(null)

    const filteredEmployees = computed(() => {
      if (!searchQuery.value) return employees.value
      return employees.value.filter(emp => 
        emp.username.toLowerCase().includes(searchQuery.value.toLowerCase())
      )
    })

    const fetchEmployees = async () => {
      try {
        const response = await axios.get('/api/users', {
          headers: { Authorization: `Bearer ${authStore.token}` }
        })
        employees.value = response.data.filter(u => u.role === 'employee')
      } catch (error) {
        ElMessage.error('获取员工列表失败')
      }
    }

    const handleEmployeeSelect = (index) => {
      selectedEmployeeId.value = index
      selectedEmployee.value = employees.value.find(e => e.id.toString() === index)
      fetchReports()
    }

    const fetchReports = async () => {
      if (!selectedEmployeeId.value) return
      
      loadingReports.value = true
      try {
        const response = await axios.get(`/api/reports/${reportType.value}`, {
          params: { userId: selectedEmployeeId.value },
          headers: { Authorization: `Bearer ${authStore.token}` }
        })
        reports.value = response.data
      } catch (error) {
        ElMessage.error('获取报告失败')
        reports.value = []
      } finally {
        loadingReports.value = false
      }
    }

    const formatDate = (date) => {
      return dayjs(date).format('YYYY-MM-DD HH:mm')
    }

    const getTimelineColor = (report) => {
      return '#409eff'
    }

    const getReportTitle = (report) => {
      if (reportType.value === 'weekly') {
        return `${report.year}年 第${report.week}周周报`
      } else if (reportType.value === 'monthly') {
        return `${report.year}年 ${report.month}月月报`
      } else {
        return `${report.year}年度报告`
      }
    }
    
    const getReportStatus = (report) => {
      return '已提交'
    }

    // Department Report Generation
    const generateDepartmentReport = async () => {
      if (!generateForm.value.date) {
        ElMessage.warning('请选择时间范围')
        return
      }
      
      generating.value = true
      try {
        let payload = {
          type: generateForm.value.type
        }
        
        const date = dayjs(generateForm.value.date)
        payload.year = date.year()
        
        if (generateForm.value.type === 'weekly') {
          // Calculate week number. Note: Element Plus week picker returns date of the week
          // We need to ensure we send the correct week number expected by backend
          // This might need adjustment based on how backend calculates weeks
           // Using a simple approximation or library function if available
           // For now, let's assume the user selects a date and we extract week
           // Note: dayjs week() requires plugin
           // Let's send the date string and let backend handle or use simple calculation
           // Actually, let's just use the ISO week if possible, or just pass the date
           // Backend expects 'week' number.
           // Let's try to get week number from the date object directly if possible or use a library
           // Since we don't have dayjs week plugin loaded by default, we might need to be careful.
           // Let's assume standard ISO week.
           
           // Hacky week calculation if dayjs plugin not available
           const d = new Date(generateForm.value.date);
           d.setHours(0, 0, 0, 0);
           d.setDate(d.getDate() + 3 - (d.getDay() + 6) % 7);
           const week1 = new Date(d.getFullYear(), 0, 4);
           const week = 1 + Math.round(((d.getTime() - week1.getTime()) / 86400000 - 3 + (week1.getDay() + 6) % 7) / 7);
           
           payload.week = week
           payload.month = date.month() + 1
        } else if (generateForm.value.type === 'monthly') {
          payload.month = date.month() + 1
        }
        
        const response = await axios.post('/api/reports/department/generate', payload, {
          headers: { Authorization: `Bearer ${authStore.token}` }
        })
        
        generatedReport.value = {
          content: response.data.report,
          title: response.data.title
        }
        ElMessage.success('部门报告生成成功')
        
      } catch (error) {
        console.error(error)
        ElMessage.error('生成失败: ' + (error.response?.data?.error || error.message))
      } finally {
        generating.value = false
      }
    }

    // Saved Reports
    const savedReports = ref([])
    const loadingSavedReports = ref(false)
    
    const fetchSavedReports = async () => {
      loadingSavedReports.value = true
      try {
        const response = await axios.get('/api/reports/department', {
          headers: { Authorization: `Bearer ${authStore.token}` }
        })
        savedReports.value = response.data
      } catch (error) {
        ElMessage.error('获取已保存报告失败')
      } finally {
        loadingSavedReports.value = false
      }
    }

    const copyReport = () => {
      navigator.clipboard.writeText(generatedReport.value.content)
      ElMessage.success('已复制到剪贴板')
    }

    const copyContent = (content) => {
      navigator.clipboard.writeText(content)
      ElMessage.success('已复制到剪贴板')
    }

    const saveDepartmentReport = async () => {
      if (!generatedReport.value) return
      
      try {
        const date = dayjs(generateForm.value.date)
        let payload = {
          type: generateForm.value.type,
          year: date.year(),
          content: generatedReport.value.content
        }
        
        if (generateForm.value.type === 'weekly') {
           const d = new Date(generateForm.value.date);
           d.setHours(0, 0, 0, 0);
           d.setDate(d.getDate() + 3 - (d.getDay() + 6) % 7);
           const week1 = new Date(d.getFullYear(), 0, 4);
           const week = 1 + Math.round(((d.getTime() - week1.getTime()) / 86400000 - 3 + (week1.getDay() + 6) % 7) / 7);
           
           payload.week = week
           payload.month = date.month() + 1
        } else if (generateForm.value.type === 'monthly') {
          payload.month = date.month() + 1
        }
        
        await axios.post('/api/reports/department/save', payload, {
          headers: { Authorization: `Bearer ${authStore.token}` }
        })
        
        ElMessage.success('报告已保存')
        fetchSavedReports()
      } catch (error) {
        ElMessage.error('保存失败')
      }
    }
    
    watch(activeTab, (val) => {
      if (val === 'saved-reports') {
        fetchSavedReports()
      }
    })

    onMounted(() => {
      fetchEmployees()
    })

    return {
      activeTab,
      employees,
      filteredEmployees,
      searchQuery,
      selectedEmployeeId,
      selectedEmployee,
      handleEmployeeSelect,
      reportType,
      reports,
      loadingReports,
      fetchReports,
      formatDate,
      getTimelineColor,
      getReportTitle,
      getReportStatus,
      generateForm,
      generating,
      generatedReport,
      generateDepartmentReport,
      copyReport,
      saveDepartmentReport,
      savedReports,
      loadingSavedReports,
      copyContent
    }
  }
}
</script>

<style scoped>
.department-reports {
  height: calc(100vh - 140px);
  background: white;
  border-radius: 8px;
  padding: 20px;
}

.main-tabs {
  height: 100%;
}

.employee-reports-container {
  display: flex;
  height: 100%;
  gap: 20px;
}

.sidebar {
  width: 250px;
  border-right: 1px solid #eee;
  padding-right: 20px;
  display: flex;
  flex-direction: column;
}

.sidebar-header {
  padding-bottom: 15px;
}

.employee-menu {
  border-right: none;
}

.main-content {
  flex: 1;
  overflow-y: auto;
  padding-right: 10px;
}

.report-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.report-card {
  margin-bottom: 10px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.report-title {
  font-weight: bold;
}

.department-generate-container {
  max-width: 800px;
  margin: 0 auto;
}

.generate-card {
  margin-top: 20px;
}

.report-preview-container {
  margin-top: 30px;
  border-top: 1px solid #eee;
  padding-top: 20px;
}

.preview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.saved-reports-container {
  padding: 20px;
  height: 100%;
  overflow-y: auto;
}
</style>
